package club.gskj.gulimall.order.listener;


import club.gskj.gulimall.order.entity.OrderEntity;
import club.gskj.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/***
 *  订单(延迟队列)定时关闭 监听器MQ
 */
@RabbitListener(queues = {"order.release.order.queue"})
@Service
public class OrderCloseMQListener {

    @Autowired
    OrderService orderService;

    @RabbitHandler
    public void listener(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
        System.out.println("收到过期的订单信息，准备关闭订单 " + orderEntity.getOrderSn());
        // 判断当前消息是否为 第二次即二次之后的重新发送， 如果为第一次发送为 true, 第一次以上为 false, 可以根据此状态判断该消息是否已经处理过了
        // TODO 订单关闭后，调用支付宝关单请求，关闭此次交易窗口。
        Boolean redelivered = message.getMessageProperties().getRedelivered();
        try {
            orderService.orderClose(orderEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
